from functools import wraps

from flask import render_template, jsonify, request, session
from werkzeug.exceptions import abort


def template_or_json(template=None):
    '''Return a dict from your view and this will either
    pass it to a template or render json. Use like:

    @template_or_json('template.html')

    '''

    def decorated(f):
        @wraps(f)
        def decorated_fn(*args, **kwargs):
            ctx = f(*args, **kwargs)
            if request.is_xhr or not template:
                return jsonify(ctx)
            else:
                return render_template(template, **ctx)

        return decorated_fn

    return decorated


def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not session.get('logged_in', None):
            return abort(403)
        return f(*args, **kwargs)
    return decorated_function


_data = [
    {
        'id': 1,
        'title': '梦陨篇章：重生',
        'category': '冒险游戏',
        'logo': 'dreamfall_chapters65.jpg'
    },
    {
        'id': 2,
        'title': '灵异女孩',
        'category': '冒险游戏',
        'logo': 'whisperingwillows65.jpg'
    },
    {
        'id': 3,
        'title': '都市运输2',
        'category': '策略游戏',
        'logo': 'citiesinmotion265.jpg'
    }
]

def get_games_from_db():
    # 为了方便，不读数据库了
    return _data

def get_game(game_id):
    game_id = int(game_id)
    if game_id > len(_data):
        return None
    return _data[game_id - 1]